#!/usr/bin/env python
# -*- coding: utf-8 -*-

import httpx

UserAgent = "Mozilla/5.0 (compatible; AutoSign/0.0.1; By @MrSuM)"


class AutoSignError(Exception):
    pass


class AutoSign:
    def __init__(
        self,
        url: str,
        username: str,
        password: str,
        **kwargs,
    ):
        """
        Init AutoSign
        """
        if url.endswith("/"):
            self.url = url[:-1]
        else:
            self.url = url

        self.username = username
        self.password = password

        session = httpx.Client(http2=True, headers={"User-Agent": UserAgent}, **kwargs)
        self.session = session
        # self.cookie = None # Unable So Far

    def login(self) -> None:
        """
        Login
        """
        login_url = self.url + "/auth/login"
        login_data = {
            "identification": self.username,
            "password": self.password,
            "keep": False,
        }

        resp = self.session.get(url=login_url)
        if resp.is_error:
            raise AutoSignError(f"Failed To Get CSRF For Login.")
        index = resp.text.find('<meta name="csrf-token" content="') + 33
        csrf_token = resp.text[index : index + 40]

        resp = self.session.post(
            url=login_url,
            json=login_data,
            headers={
                "Referer": login_url,
                "Origin": self.url,
                "X-CSRF-TOKEN": csrf_token,
                "Content-Type": "application/json",
            },
            follow_redirects=True,
        )
        if resp.is_error:
            raise AutoSignError(f"Failed To Post Login API.")

        resp_json = resp.json()
        if resp_json["code"] != 0:
            if resp_json["message"] is not None:
                raise AutoSignError(f"Failed To Login. Reason: {resp_json}")
            else:
                raise AutoSignError(f"Failed To Login. Reason: {resp_json["message"]}")

    def sign(self) -> None:
        """
        Sign
        """
        login_url = self.url + "/auth/login"
        user_url = self.url + "/user"
        sign_url = self.url + "/user/sign"

        resp = self.session.get(
            url=user_url,
            headers={"Referer": login_url},
            follow_redirects=True,
        )
        if resp.is_error:
            raise AutoSignError(f"Failed To Get CSRF For Sign API.")
        index = resp.text.find('<meta name="csrf-token" content="') + 33
        csrf_token = resp.text[index : index + 40]

        resp = self.session.post(
            url=sign_url,
            headers={
                "Referer": user_url,
                "Origin": self.url,
                "X-CSRF-TOKEN": csrf_token,
                "Content-Type": "application/json",
            },
        )
        if resp.is_error:
            raise AutoSignError(f"Failed To Post Sign.")

        resp_json = resp.json()
        if resp_json["code"] != 0:
            if resp_json["message"] == "":
                raise AutoSignError(f"Failed To Sign. Reason: {resp_json}")
            else:
                raise AutoSignError(f"Failed To Sign. Reason: {resp_json["message"]}")
            # raise AutoSignError(f"Failed To Sign. Reason: {resp_json}")


if __name__ == "__main__":
    """
    Quick Start
    """
    url = "https://skin.example.com"
    username = "username"
    password = "password"

    auto_sign = AutoSign(
        url=url,
        username=username,
        password=password,
    )

    auto_sign.login()
    print("Login Successfully.")

    auto_sign.sign()
    print("Sign Successfully.")
